package com.naihe.anderson.sms.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.naihe.anderson.sms.R;
import com.naihe.anderson.sms.application.NhSmsApp;
import com.naihe.anderson.sms.constants.NhSmsConstants;
import com.naihe.anderson.sms.entity.Geoloc;
import com.naihe.anderson.sms.entity.RecordMoney;
import com.naihe.anderson.sms.manager.RecordMoneyMgr;
import com.naihe.anderson.sms.util.AsyncImageLoader;
import com.naihe.anderson.sms.util.AsyncImageLoader.ImageCallback;
import com.naihe.anderson.sms.util.FileUtil;
import com.naihe.anderson.sms.widgets.InfoAlertDialog;
import com.naihe.anderson.sms.widgets.LongClickDialog;

public class NewIncomeActivity extends Activity implements OnClickListener{
	public static final int CONFIRM_BACK = 3047;
	
	NhSmsApp nhSmsApp;
	RecordMoneyMgr moneyMgr;
	
	Button back_btn;
	Button create_btn;
	Button income_project_btn;
	Button income_projectpic_btn;
	Button income_map_btn;
	
	EditText income_project_et;
	EditText income_number_et;
	EditText income_objectMember_et;
	EditText income_remarks_et;
	
	ImageView income_projectpic_img;
	ImageView income_map_img;
	
	private final static int MSG_WHAT_SHOW_NOPROJECTINFO = 0;
	private final static int MSG_WHAT_SHOW_PROJECT_CHOICE = 1;
	
	private static int SELECT_PICTURE_SYSCERAME = 2;// 返回标志位 filed
	private static int SELECT_PICTURE = 3;// 返回标志位 filed
	private File tempFile;
	private String monryAddressPicName = "";
	private Geoloc geoloc;
	
	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_WHAT_SHOW_NOPROJECTINFO:
				new InfoAlertDialog(NewIncomeActivity.this, null, "暂无数据，在按钮左边输入即可自动保存！", "", null).show();
				break;
			case MSG_WHAT_SHOW_PROJECT_CHOICE:
				final List<String> income = moneyMgr.getIncome();
				String[] links = income.toArray(new String[income.size()]);
				
				new LongClickDialog(NewIncomeActivity.this, links, "选择", new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
						income_project_et.setText(income.get(position));
					}
				}).show();
				break;
			default:
				break;
			}
		}
		
	};
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_income_layout);
		
		nhSmsApp = (NhSmsApp) getApplication();
		nhSmsApp.setActivity(this);
		moneyMgr = nhSmsApp.getRecordMoneyMgr();
		
		initView();
	}
	
	private void initView(){
		back_btn = (Button) findViewById(R.id.back_btn);
		back_btn.setOnClickListener(this);
		create_btn = (Button) findViewById(R.id.create_btn);
		create_btn.setOnClickListener(this);
		income_project_btn = (Button) findViewById(R.id.income_project_btn);
		income_project_btn.setOnClickListener(this);
		income_projectpic_btn = (Button) findViewById(R.id.income_projectpic_btn);
		income_projectpic_btn.setOnClickListener(this);
		income_map_btn = (Button) findViewById(R.id.income_map_btn);
		income_map_btn.setOnClickListener(this);
		
		income_number_et = (EditText) findViewById(R.id.income_number_et);
		income_project_et = (EditText) findViewById(R.id.income_project_et);
		income_objectMember_et = (EditText) findViewById(R.id.income_objectMember_et);
		income_remarks_et = (EditText) findViewById(R.id.income_remarks_et);
		
		income_projectpic_img = (ImageView) findViewById(R.id.income_projectpic_img);//
		income_map_img = (ImageView) findViewById(R.id.income_map_img);
	}

	private void toFinishActivity(){
		tempFile = null;
		nhSmsApp.setActivity(null);
		if(geoloc != null && !TextUtils.isEmpty(geoloc.getMappicname())){
			File file = new File(FileUtil.getPicNotePath() + geoloc.getMappicname());
			if(file.exists()) file.delete();
		}
		
		if(!TextUtils.isEmpty(monryAddressPicName)){
			File file =  new File(FileUtil.getPicNotePath() + monryAddressPicName);
			if(file.exists()) file.delete();
		}
		NewIncomeActivity.this.finish();
		System.gc();
	}
	
	private void toCreateincome(){
		String number = income_number_et.getText().toString();
		if(TextUtils.isEmpty(number)){
			Toast.makeText(NewIncomeActivity.this, "金额没有填写", Toast.LENGTH_SHORT).show();
			income_number_et.requestFocus();
			return;
		}
		String project = income_project_et.getText().toString();
		if(TextUtils.isEmpty(number)){
			Toast.makeText(NewIncomeActivity.this, "项目没有填写", Toast.LENGTH_SHORT).show();
			return;
		}
		String objectMember = income_objectMember_et.getText().toString();
		if(TextUtils.isEmpty(number)){
			Toast.makeText(NewIncomeActivity.this, "成员没有填写", Toast.LENGTH_SHORT).show();
			return;
		}
		
		RecordMoney recordMoney = new RecordMoney();
		recordMoney.actionType = RecordMoney.ACTION_TYPE_INCOME;
		recordMoney.createTime = new Date().getTime();
		recordMoney.loation = geoloc == null ? "" : geoloc.getMappicname() + "/" + geoloc.getLat() + "/" + geoloc.getLon();
		recordMoney.moneyNum = Float.parseFloat(number);
		recordMoney.objectMember = objectMember;
		recordMoney.project = project;
		recordMoney.projectPic = monryAddressPicName;
		recordMoney.remarks = income_remarks_et.getText().toString();
		recordMoney.rmid = recordMoney.createTime;
		
		moneyMgr.insertRecordMoney(recordMoney);
		if(tempFile != null && tempFile.exists()) tempFile.delete();
		tempFile = null;
		nhSmsApp.setActivity(null);
		NewIncomeActivity.this.finish();
		System.gc();
	}
	
	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.back_btn){
			toFinishActivity();
		} else if(v.getId() == R.id.create_btn){
			toCreateincome();
		} else if(v.getId() == R.id.income_project_btn){
			if(moneyMgr.getIncomeSize() == 0){
				handler.sendEmptyMessage(MSG_WHAT_SHOW_NOPROJECTINFO);
			} else {
				handler.sendEmptyMessage(MSG_WHAT_SHOW_PROJECT_CHOICE);
			}
		} else if(v.getId() == R.id.income_projectpic_btn){
			if(TextUtils.isEmpty(FileUtil.getPicNotePath())){
				Toast.makeText(NewIncomeActivity.this, R.string.sderror, Toast.LENGTH_SHORT).show();
				return;
			}
			
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
			//下面这句指定调用相机拍照后的照片存储的路径 
			if(tempFile == null) {
				tempFile = new File(FileUtil.getPicNotePath() + NhSmsConstants.PICNOTE_TEMP_NAME);
				monryAddressPicName = NhSmsConstants.MONRY_PREFIX + new Date().getTime() + ".png";
			}
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile)); 
			startActivityForResult(intent, SELECT_PICTURE_SYSCERAME);
		} else if(v.getId() == R.id.income_map_btn){
			getMap();
		}
	}
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 截获按键事件
        if(KeyEvent.KEYCODE_BACK == keyCode){
        	toFinishActivity();
        	return true;
		}

        return super.onKeyDown(keyCode, event);
    }
	
	private void getMap(){
		try {
            Class.forName("com.google.android.maps.MapActivity");
        } catch (Exception e) {
            Intent intent = new Intent(NewIncomeActivity.this, WebMapActivity.class);
            NewIncomeActivity.this.startActivityForResult(intent, CONFIRM_BACK);
            return;
        }
        Intent intent = new Intent(NewIncomeActivity.this, MapViewActivity.class);
        NewIncomeActivity.this.startActivityForResult(intent, CONFIRM_BACK);
	}
	
	/**
	 * 裁剪完图片后系统调用的方法:onActivityResult
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK){
			if(requestCode == SELECT_PICTURE_SYSCERAME){
				startPhotoZoom(Uri.fromFile(tempFile));
			} else if(requestCode == SELECT_PICTURE){
				if(data != null){
					setPicToView(data);
				}
			} else if(requestCode == CONFIRM_BACK){
				setMapPicToView(data);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	private void setMapPicToView(Intent picdata){
		geoloc = (Geoloc) picdata.getExtras().get("geoloc");
		geoloc.setMappicname(NhSmsConstants.MONRY_MAP_PREFIX + new Date().getTime() + ".png");
		String url = NhSmsConstants.STATICMAP_URL.replaceAll("LAT", String.valueOf(geoloc.getLat())).replaceAll("LON", String.valueOf(geoloc.getLon()));
		new AsyncImageLoader(NhSmsConstants.PIC_WIDTH, NhSmsConstants.PIC_HEIGHT).loadImageFromUrl(url, geoloc.getMappicname(), new ImageCallback() {
			
			@Override
			public void imageLoaded(Bitmap obj) {
				income_map_img.setImageBitmap(obj);
			}
		});
	}
	
	private void setPicToView(Intent picdata) {
		Bitmap bitmap = getLoacalBitmap(monryAddressPicName);
		income_projectpic_img.setImageBitmap(bitmap);
	}
	
	private Bitmap getLoacalBitmap(String draw_name) {
		try {
			BitmapFactory.Options opt = new BitmapFactory.Options();
			opt.inSampleSize = 1;
			opt.inPreferredConfig = Bitmap.Config.RGB_565;
			opt.inPurgeable = true;
			opt.inInputShareable = true; // 获取资源图片
			FileInputStream fis = new FileInputStream(FileUtil.getPicNotePath() + draw_name);
			return BitmapFactory.decodeStream(fis, null, opt);
		} catch (FileNotFoundException e) {
			return null;
		}
	}
	
	private void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");//设置要裁剪的图片
		intent.putExtra("crop", "true");// crop=true 有这句才能出来最后的裁剪页面.
		intent.putExtra("aspectX", 2);// 这两项为裁剪框的比例.
		intent.putExtra("aspectY", 3);// x:y=2:3
		// 如果不设置aspectX和aspectY，则可以以任意比例缩放
		intent.putExtra("outputX", NhSmsConstants.PIC_WIDTH);
	    intent.putExtra("outputY", NhSmsConstants.PIC_HEIGHT);
	    // 输出图片的宽
		intent.putExtra("output", Uri.fromFile(new File(FileUtil.getPicNotePath() + monryAddressPicName)));//保存到原文件
		intent.putExtra("outputFormat", "JPEG");// 返回格式

		startActivityForResult(Intent.createChooser(intent, "裁剪"), SELECT_PICTURE);
	}
}
